/* eslint-disable prettier/prettier */
import React, {Component} from 'react';
import {AnimatedCircularProgress} from 'react-native-circular-progress';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Button,
  BackHandler,
  ToastAndroid,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

import Video from 'react-native-video';

function formatTime(second) {
  let h = 0,
    i = 0,
    s = parseInt(second);
  if (s > 60) {
    i = parseInt(s / 60);
    s = parseInt(s % 60);
  }
  // 补零
  let zero = function (v) {
    return v >> 0 < 10 ? '0' + v : v;
  };
  console.log([zero(h), zero(i), zero(s)].join(':'));
  // return [zero(h), zero(i), zero(s)].join(":");
  return zero(s);
}

export default class Player extends Component {
  static navigationOptions = {
    header: null,
  };

  state = {
    rate: 1,
    volume: 1,
    muted: false,
    resizeMode: 'contain',
    duration: 0.0,
    currentTime: 0.0,
    paused: true,
    showview: false,
    url: '',
    type: 'play',
    Buffer: true,
    fill: 0,
    load: false,
    res: null,
    api: '',
  };
  show(obj) {
    this.setState({showview: true});
  }
  close() {
    this.setState({showview: false});
  }
  UNSAFE_componentWillMount() {
    this.setState({url: this.props.route.params.url});
    this.setState({type: this.props.route.params.type});
    this.setState({api: this.props.route.params.api});

    BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
  }

  onBackAndroid = () => {
    this.props.navigation.goBack();
    return true;
  };

  onLoad = (data) => {
    this.setState({duration: data.duration});
    ToastAndroid.show('视频加载成功！', ToastAndroid.SHORT);
    console.log(data.duration + 'xxx');
  };

  onProgress = (data) => {
    this.setState({currentTime: data.currentTime});
    console.log(data.currentTime + 'hhh');
  };
  onBuffer = () => {
    this.setState({Buffer: !this.state.Buffer});
    if (this.state.Buffer) {
      ToastAndroid.show('正在缓冲请稍等', ToastAndroid.LONG);
    }
  };
  onEnd = () => {
    this.setState({paused: true});
    this.video.seek(0);
  };

  onAudioBecomingNoisy = () => {
    this.setState({paused: true});
  };

  onAudioFocusChanged = (event: {hasAudioFocus: boolean}) => {
    this.setState({paused: !event.hasAudioFocus});
  };

  getCurrentTimePercentage() {
    if (this.state.currentTime > 0) {
      return (
        parseFloat(this.state.currentTime) / parseFloat(this.state.duration)
      );
    }
    return 0;
  }

  renderRateControl(rate) {
    const isSelected = this.state.rate === rate;

    return (
      <TouchableOpacity
        onPress={() => {
          this.setState({rate});
        }}>
        <Text
          style={[
            styles.controlOption,
            {fontWeight: isSelected ? 'bold' : 'normal'},
          ]}>
          {rate}x
        </Text>
      </TouchableOpacity>
    );
  }

  renderResizeModeControl(resizeMode) {
    const isSelected = this.state.resizeMode === resizeMode;

    return (
      <TouchableOpacity
        onPress={() => {
          this.setState({resizeMode});
        }}>
        <Text
          style={[
            styles.controlOption,
            {fontWeight: isSelected ? 'bold' : 'normal'},
          ]}>
          {resizeMode}
        </Text>
      </TouchableOpacity>
    );
  }

  renderVolumeControl(volume) {
    const isSelected = this.state.volume === volume;
    return (
      <TouchableOpacity
        onPress={() => {
          this.setState({volume});
        }}>
        <Text
          style={[
            styles.controlOption,
            {fontWeight: isSelected ? 'bold' : 'normal'},
          ]}>
          {volume * 100}%
        </Text>
      </TouchableOpacity>
    );
  }
  btn() {
    if (this.state.type === 'play') {
      return null;
    } else {
      if (!this.state.load) {
        return (
          <View>
            <Button
              style={styles.btnStyle}
              title={'确定上传'}
              color={'#73808080'}
              onPress={() => {
                this.uploadImage(this.state.url);
              }}
            />
          </View>
        );
      } else {
        return null;
      }
    }
  }

  loading() {
    if (this.state.load) {
      return (
        <AnimatedCircularProgress
          ref={(ref) => (this.circularProgress = ref)}
          size={60}
          width={10}
          fill={this.state.fill}
          style={styles.loading}
          tintColor="#00e0ff"
          onAnimationComplete={() => {
            console.log('onAnimationComplete');
          }}
          backgroundColor="#3d5875"
        />
      );
    } else {
      return null;
    }
  }
  play() {
    return (
      <Video
        ref={(ref: Video) => {
          this.video = ref;
        }}
        /* For ExoPlayer */
        source={{uri: this.state.url}}
        style={styles.fullScreen}
        rate={this.state.rate}
        paused={this.state.paused}
        volume={this.state.volume}
        muted={this.state.muted}
        resizeMode={this.state.resizeMode}
        onLoad={this.onLoad}
        onProgress={this.onProgress}
        onBuffer={this.onBuffer}
        onEnd={this.onEnd}
        onAudioBecomingNoisy={this.onAudioBecomingNoisy}
        onAudioFocusChanged={this.onAudioFocusChanged}
        repeat={false}
        fullscreen={true}
        controls={true}
        automaticallyWaitsToMinimizeStalling={true}
        bufferConfig={{
          minBufferMs: 30000,
          maxBufferMs: 30000,
          bufferForPlaybackMs: 2500,
          bufferForPlaybackAfterRebufferMs: 5000,
        }}
      />
    );
  }
  showplay() {
    if (this.state.paused) {
      return <Button style={styles.btnStyle} title={'暂停'} />;
    } else {
      return <Button style={styles.btnStyle} title={'正在播放'} />;
    }
  }
  render() {
    // const flexCompleted = this.getCurrentTimePercentage() * 100
    // const flexRemaining = (1 - this.getCurrentTimePercentage()) * 100

    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.fullScreen}>
          {this.play()}
          {this.loading()}
        </TouchableOpacity>

        <View style={styles.textStyle}>
          <Text
            style={styles.volumeControl}
            onPress={() => {
              this.props.navigation.goBack();
            }}>
            {/* { formatTime(this.state.duration - this.state.currentTime) } */}
            <Icon name={'angle-left'} size={30} color={'#fff'} />
          </Text>
          {/* {this.showplay()} */}
          {this.btn()}
        </View>

        {/* <View style={styles.controls}>
                    <View style={styles.generalControls}>

                    </View>

                    <View style={styles.trackingControls}>
                        <View style={styles.progress}>
                            <View style={[styles.innerProgressCompleted, {flex: flexCompleted}]}/>
                            <View style={[styles.innerProgressRemaining, {flex: flexRemaining}]}/>
                        </View>
                    </View>
                </View> */}
      </View>
    );
  }

  /**************文件上传**************/
  uploadImage(file) {
    this.setState({load: true}, () => {
      // this.props.route.params.fun(file);
      // this.props.navigation.goBack();
      this.circularProgress.animate(80, 4000);
      var uploadUrl = this.state.api;
      let formData = new FormData();
      let files = {uri: file, type: 'video/mp4', name: 'test'};
      formData.append('file', files);
      formData.append('type', '.mp4');
      fetch(uploadUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8',
        },
        body: formData,
      })
        .then((response) => response.json())
        .then((responseData) => {
          if (responseData.code === 0) {
            this.circularProgress.animate(100, 200);
            this.props.route.params.fun(responseData.result);
            this.props.navigation.goBack();
          } else {
            ToastAndroid.show(responseData.msg, ToastAndroid.SHORT);
            this.setState({load: false});
          }
        })
        .catch((err) => {
          console.log('err', err);
          this.setState({load: false});
          ToastAndroid.show('上传失败', ToastAndroid.SHORT);
        });
    });
  }
}

const styles = StyleSheet.create({
  loading: {
    width: 60,
    height: 60,
    position: 'absolute',
    top: '50%',
    left: '45%',
  },
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
    backgroundColor: '#000000',
  },
  icon: {
    position: 'absolute',
    top: 20,
    left: 20,
    bottom: 0,
    right: 0,
    color: '#fff',
  },
  textStyle: {
    paddingLeft: 10,
    paddingTop: 25,
    justifyContent: 'flex-start',
    flexDirection: 'row',
    position: 'absolute',
    top: 20,
    left: 20,
    right: 20,
  },
  btnStyle: {
    marginTop: 10,
    paddingRight: 10,
    paddingTop: 25,
    justifyContent: 'flex-end',
    flexDirection: 'row',
  },
  fullScreen: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
  controls: {
    backgroundColor: 'transparent',
    borderRadius: 5,
    position: 'absolute',
    bottom: 20,
    left: 20,
    right: 20,
  },
  progress: {
    flex: 1,
    flexDirection: 'row',
    borderRadius: 3,
    overflow: 'hidden',
  },
  innerProgressCompleted: {
    height: 20,
    backgroundColor: '#cccccc',
  },
  innerProgressRemaining: {
    height: 20,
    backgroundColor: '#2C2C2C',
  },
  generalControls: {
    flex: 1,
    flexDirection: 'row',
    borderRadius: 4,
    overflow: 'hidden',
    paddingTop: 10,
  },
  rateControl: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  volumeControl: {
    fontSize: 25,
    color: '#fff',
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  resizeModeControl: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  controlOption: {
    alignSelf: 'center',
    fontSize: 11,
    color: 'white',
    paddingLeft: 2,
    paddingRight: 2,
    lineHeight: 12,
  },
});
